﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Xml;
using BSF.Tool;
using HuntingFishGame.ManageDomain.BLL.WeChat;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace HuntingFishGame.H5.Controllers
{
    public class SendTemplateController : Controller
    {
        private readonly string access_token = WeixinConfig.BaseAccessToken(WeixinType.CertServiceAccount).ParamValue;
        public string sendxml = "";
        // GET: SendTemplate
        public ActionResult Index()
        {
            #region 判断是否有该IP
            string ip = CommonHelper.ClientIp();
            XmlDocument doc = new XmlDocument();
            string url2 = Server.MapPath("~/Config/About.config");
            doc.Load(url2);
            XmlNode root = doc.SelectSingleNode("data");
            XmlNode typeNode = root.SelectSingleNode("ips");
            // 得到根节点的所有子节点
            XmlNodeList xnl = typeNode.ChildNodes;
            string value = "";
            foreach (XmlNode xn1 in xnl)
            {
                // 将节点转换为元素，便于得到节点的属性值
                XmlElement xe = (XmlElement)xn1;
                // 得到Type和ISBN两个属性的属性值
                if (xe.GetAttribute("value").ToString() == ip)
                {
                    value = xe.GetAttribute("value").ToString();
                    break;
                }
            }
            if (string.IsNullOrEmpty(value))
            {
                LogClass log = new LogClass();
                string logContent = "发送验证码通知：没有该IP:" + ip + ",时间为：" + DateTime.Now.ToString();
                string url3 = "log\\" + DateTime.Now.ToString("yyyy-MM-dd") + "log.txt";
                log.WriteLog(logContent, Server.MapPath(url3));
                sendxml = "100";//没有该IP
            }
            else
            {
                string url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + access_token;//GetCode.Code//发送验证码的URL
                string content = this.GetContent();//发送验证码的内容
                if (string.IsNullOrEmpty(sendxml))
                {
                    GetPage(url, content);
                }
            }
            #endregion

            //return View();
            //给模板发消息
            //Response.Write(sendxml);
            return Content(sendxml, "text/plain", Encoding.UTF8);//第二个参数就是：MIME类型
        }

        #region 给模板发送消息
        /// <summary>
        /// 给模板发送消息
        /// </summary>
        /// <param name="posturl"></param>
        /// <param name="postData"></param>
        /// <returns></returns>
        public string GetPage(string posturl, string postData)
        {
            Stream outstream = null;
            Stream instream = null;
            StreamReader sr = null;
            HttpWebResponse response = null;
            HttpWebRequest request = null;
            Encoding encoding = Encoding.UTF8;
            byte[] data = encoding.GetBytes(postData);
            // 准备请求...
            try
            {
                // 设置参数
                request = WebRequest.Create(posturl) as HttpWebRequest;
                CookieContainer cookieContainer = new CookieContainer();
                request.CookieContainer = cookieContainer;
                request.AllowAutoRedirect = true;
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                request.ContentLength = data.Length;
                outstream = request.GetRequestStream();
                outstream.Write(data, 0, data.Length);
                outstream.Close();
                //发送请求并获取相应回应数据
                response = request.GetResponse() as HttpWebResponse;
                //直到request.GetResponse()程序才开始向目标网页发送Post请求
                instream = response.GetResponseStream();
                sr = new StreamReader(instream, encoding);
                //返回结果网页（html）代码
                string content = sr.ReadToEnd();
                string err = string.Empty;
                if (!string.IsNullOrEmpty(content))
                {
                    JObject jo = (JObject)JsonConvert.DeserializeObject(content);
                    if (jo["errcode"] != null && jo["errcode"].ToString() == "42001")//access_token 超时
                    {
                        //GetCode getCode = new GetCode();
                        //getCode.GetCodeValue();
                        //根据模板给微信账户发消息
                        string getContent = this.GetContent();
                        GetPage("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + access_token, getContent);//GetCode.Code
                    }
                    if (jo["errcode"] != null && jo["errcode"].ToString() == "0")
                    {
                        sendxml = "0";
                    }
                    else if (jo["errcode"].ToString() == "40001")
                    {
                        content = content + " 错误：40001，访问URL为：" + posturl + " 发送内容为：" + postData;
                        //GetCode getCode = new GetCode();
                        //getCode.GetCodeValue();
                        //根据模板给微信账户发消息
                        string getContent = this.GetContent();
                        GetPage("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + access_token, getContent);//GetCode.Code
                    }
                    else if (jo["errcode"] != null && jo["errcode"].ToString() != "42001")
                    {
                        sendxml = "-1";
                    }

                    LogClass log = new LogClass();
                    string logContent = "发送验证码通知：" + content + ",时间为：" + DateTime.Now.ToString();
                    string url = "log\\" + DateTime.Now.ToString("yyyy-MM-dd") + "log.txt";
                    log.WriteLog(logContent, Server.MapPath(url));
                }
                return content;
            }
            catch (Exception ex)
            {
                string err = ex.Message;
                return string.Empty;
            }
        }
        #endregion

        #region 获取发送内容
        /// <summary>
        /// 获取发送内容
        /// </summary>
        /// <returns></returns>
        public string GetContent()
        {
            string content = "";
            if (Request.Params["opID"] != null)//用户微信ＩＤ
            {
                string mbcode = "";
                if (!string.IsNullOrEmpty(Helper.GetConfig("mbcode")))
                {
                    mbcode = Helper.GetConfig("mbcode");
                }

                content = "{\"touser\":\"" +
                    Request.Params["opID"].ToString()
                       + "\",\"template_id\":\"" +
                       mbcode
                       + "\",\"topcolor\":\"#FF0000\",\"data\":{\"first\": {\"value\":";
            }
            else
            {
                sendxml = "1";
            }
            if (Request.Params["UID"] != null)　//游戏ID
            {
                content += " \"游戏账号ID：" + Request.Params["UID"].ToString();
            }
            else
            {
                sendxml = "2";
            }
            //类型
            if (Request.Params["type"] != null)
            {
                XmlDocument doc = new XmlDocument();
                string url = Server.MapPath("~/Config/About.config");
                doc.Load(url);
                XmlNode root = doc.SelectSingleNode("data");
                XmlNode typeNode = root.SelectSingleNode("types");
                // 得到根节点的所有子节点
                XmlNodeList xnl = typeNode.ChildNodes;
                string value = "";
                foreach (XmlNode xn1 in xnl)
                {
                    // 将节点转换为元素，便于得到节点的属性值
                    XmlElement xe = (XmlElement)xn1;
                    // 得到Type和ISBN两个属性的属性值
                    string id = xe.GetAttribute("ISBN").ToString();

                    if (xe.GetAttribute("id").ToString() == Request.Params["type"].ToString())
                    {
                        value = xe.GetAttribute("value").ToString();
                        break;
                    }
                }
                if (string.IsNullOrEmpty(value))
                {
                    content += ".\",";
                }
                else
                {
                    content += value + ".\","; ;
                }
                content += "\"color\":\"#173177\"},\"keyword1\":{\"value\":";
            }
            else
            {
                sendxml = "3";
            }
            if (Request.Params["code"] != null)
            {
                content += "\"" + Request.Params["code"].ToString() + "\",\"color\":\"#173177\"},";
            }
            else
            {
                sendxml = "4";
            }
            content += "\"keyword2\":{\"value\":\"5分钟\",\"color\":\"#173177\"},\"remark\":{\"value\":\"猎鱼岛游戏\",\"color\":\"#173177\"}}}";

            Helper.ExtLog("发送消息模板内容：" + content);
            return content;
        }
        #endregion

    }
}